//
//  MAUserEditInfoController.m
//  meiang_edu
//
//  Created by hfcb on 2018/9/11.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MAUserEditInfoController.h"
#import "OssService.h"
#import "NSString+Js.h"
#import "MAMgrPopView.h"
#import <zhPopupController.h>

@interface MAUserEditInfoController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *bgIcon;
@property (weak, nonatomic) IBOutlet UIImageView *faceIcon;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UILabel *sexLabel;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;

@property (strong, nonatomic) UIActionSheet *actionSheet;
/** bgImgUrl */
@property(nonatomic,copy) NSString *bgImgUrl;
/** faceImgUrl */
@property(nonatomic,copy) NSString *faceImgUrl;

@end

@implementation MAUserEditInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupBasic];
    
    [self bindData];
}

- (void)setupBasic {
    self.title = @"编辑详情";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(saveDidClick) image:@"savebutton_logo" highImage:@"savebutton_logo"];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 4)];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.backgroundColor = PROJECT_LIGHT_GRAY_COLOR;
}

- (void)bindData {
    MAUserInfo *info = [MAUserInfoTool userinfo];
    [self.bgIcon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_OSS,info.cbackground]] placeholderImage:[UIImage imageNamed:@""]];
    [self.faceIcon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_OSS,info.ps_id]] placeholderImage:[UIImage imageNamed:@"homepage_navigationbar_picture"]];
    
    self.nameTF.text = info.name;
    self.sexLabel.text = info.gender;
    self.phoneTF.text = info.ustelphone;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)saveDidClick {
    DLog(@"");
    NSString *name = self.nameTF.text;
    if (!name.length) {
        [MBManager showBriefAlert:@"姓名不能为空"];
        return;
    }
    NSString *sex = self.sexLabel.text;
    if ([sex isEqualToString:@"请选择"]) {
        [MBManager showBriefAlert:@"请选择性别"];
        return;
    }
    NSString *phone = self.phoneTF.text;
    if (!phone.length) {
        [MBManager showBriefAlert:@"请填写手机号"];
        return;
    }
    
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    
    NSMutableDictionary *body = [NSMutableDictionary dictionary];
//    "id": "102299E9-D7A7-4726-9412-B84E8B9D799C",用户ID
//    "ccode": "YH0006",会员编号
//    "cuserid": "ZF",用户编号
//    "usname": "张凡",姓名
//    "cpinyin": "zhangfan"拼音,
//    "usidentitycard": "370324198505301311",身份证号
//    "asusgender": "男",性别
//    "ps_id": "E7BDD382-3965-425E-902C-A463B8ED2295",头像ID
//    "cbackground": "E7BDD382-3965-425E-902C-A463B8ED2295",头像ID
//    "usbirthday": "1985-05-30",生日
//    "usnickname": null,昵称
//    "cnotes": null,备注
//    "denabledate": 1497858674270,
//    "ddisabledate": null

    body[@"id"] = userinfo.ID;
    body[@"ccode"] = userinfo.ccode;
    body[@"usname"] = name;
    body[@"asusgender"] = sex;
    body[@"ustelphone"] = phone;
    body[@"ps_id"] = self.faceImgUrl.length ? self.faceImgUrl : userinfo.ps_id;
    body[@"cbackground"] = self.bgImgUrl.length ? self.bgImgUrl : userinfo.cbackground;
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:USER_UPDATE parameters:nil error:nil];
    [req setValue:@"application/text" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [req setValue:@"token" forHTTPHeaderField:userinfo.token];
    
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [MBManager hideAlert];
        DLog(@"Reply JSON: %@", responseObject);
        if (!error) {
            NSInteger msgcode = [responseObject[@"msgcode"] integerValue];
            NSString *message = responseObject[@"message"];
            if (msgcode == 1) {
                [MBManager showBriefAlert:message];
                if (self.faceImgUrl.length) {
                    userinfo.ps_id = self.faceImgUrl;
                }
                if (self.bgImgUrl.length) {
                    userinfo.cbackground = self.bgImgUrl;
                }
                userinfo.usname = name;
                userinfo.usgender = sex;
                // 修改电话,木有字段
                userinfo.ustelphone = phone;
                [MAUserInfoTool saveUserInfo:userinfo];
                self.navigationItem.rightBarButtonItem = nil;
            } else {
                [MBManager showBriefAlert:message];
            }
        } else {
            DLog(@"Error: %@, %@, %@", error, response, responseObject);
            [MBManager showBriefAlert:@"网络错误"];
        }
    }] resume];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    if (row == 0) { // 更换背景
        [self chooseIcon];
        DLog(@"");
    } else if (row == 1) { // 更换logo
        DLog(@"");
        [self chooseIcon];
    } else if (row == 3) { // 选择性别
        DLog(@"");
        MAMgrPopView *popView = [MAMgrPopView popViewWithTitles:@[@"男", @"女"] clickBlock:^(NSInteger clickIdx) {
            DLog(@"%ld",clickIdx);
            self.sexLabel.text = clickIdx ? @"女" : @"男";
            [self.zh_popupController dismiss];
        }];
        
        popView.layer.cornerRadius = 10;
        popView.layer.masksToBounds = YES;
        self.zh_popupController = [[zhPopupController alloc] init];
        self.zh_popupController.dismissOnMaskTouched = YES;
        self.zh_popupController.dismissOppositeDirection = YES;
        self.zh_popupController.slideStyle = zhPopupSlideStyleShrinkInOut2;
        [self.zh_popupController presentContentView:popView duration:0.35 springAnimated:YES];
    } else {
        
    }
}

/**
 * 选择图片
 */
- (void)chooseIcon
{
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择",nil];
    }else{
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:@"取消"destructiveButtonTitle:nil otherButtonTitles:@"从相册选择",nil];
    }
    
    self.actionSheet.tag = 1000;
    [self.actionSheet showInView:self.view];
}

// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 1000) {
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            switch (buttonIndex) {
                case 0:
                    //来源:相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    //来源:相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    return;
            }
        }
        else {
            if (buttonIndex == 1) {
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    DLog(@"===========%ld",indexPath.row);
    
    // 上传头像
    OssService *ossService = [[OssService alloc] initWithEndPoint:OSS_ENDPOINT];
    NSString *category = OSS_CATEGORY;
    NSString *type = @"jpg";
    long long int timevalue = (long long int)([NSDate date].timeIntervalSince1970 * 1000);
    // 自己拼接key，用于标识对象。
    
    NSString *objectKey = [NSString uuidString];
    [ossService asyncPutImage:objectKey data:UIImageJPEGRepresentation(img, 0.5) success:^(NSString *imgUrl){
        DLog(@"%@",imgUrl);
        if (indexPath.row == 0) { // 背景
            self.bgImgUrl = [[imgUrl componentsSeparatedByString:IMG_OSS] lastObject];
            [self.bgIcon sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
        } else { // 头像
            self.faceImgUrl = [[imgUrl componentsSeparatedByString:IMG_OSS] lastObject];
            [self.faceIcon sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
        }
    } failure:^(NSString *errmsg, NSString *objectKey, NSData *uploadData) {
        DLog(@"%@",errmsg);
    }];
}
@end
